use crate::{ApiError, ApiResult, ToError, configuration};
use lettre::message::MessageBuilder;
use lettre::transport::smtp::authentication::Credentials;
use lettre::{AsyncSmtpTransport, Message, Tokio1Executor};
use std::sync::LazyLock;

static SENDER: LazyLock<AsyncSmtpTransport<Tokio1Executor>> =
    LazyLock::new(|| get_sender().expect("创建SMTP服务错误"));
fn get_sender() -> ApiResult<AsyncSmtpTransport<Tokio1Executor>> {
    let email = configuration::email();
    let creds = Credentials::new(email.username().to_string(), email.password().to_string());
    // 使用 SMTP 服务器发送
    Ok(AsyncSmtpTransport::<Tokio1Executor>::relay(email.domain())
        .to_err(|| ApiError::Biz("创建SMTP服务错误".into()))?
        .credentials(creds)
        .port(email.port())
        .build())
}

pub fn get() -> &'static AsyncSmtpTransport<Tokio1Executor> {
    &SENDER
}

/// 创建消息
pub fn message() -> ApiResult<MessageBuilder> {
    let email = configuration::email();
    let name = email.name();
    let username = email.username();
    let name = name.unwrap_or_else(|| "");
    Ok(Message::builder().from(
        format!("{} <{}>", name, username)
            .parse()
            .to_err(|| ApiError::Biz("发送人错误".into()))?,
    ))
}
